import * as THREE from 'three'
export class ClickHandler {
    static getInstance () {
        if (!this.instance) {
            // 如果不存在这个实例 则实例化一个，否则，单例模式，永远是同一个实例
            this.instance = new ClickHandler() 
        }
        return this.instance
    }

    init (camera) {
        this.camera = camera
        // 光线投射交互要求计算的物体
        this.list = []
        // map：key与点击要执行的回调函数形成一对一
        this.map = new Map()

        // 光线投射
        const rayCaster = new THREE.Raycaster()
        const pointer = new THREE.Vector2()
        const app = document.querySelector('.app')

        window.addEventListener('click', (e) => {
            pointer.x = (e.clientX / app.clientWidth) * 2 - 1
            pointer.y = -((e.clientY / app.clientHeight) * 2 - 1)
            // 通过摄像机和鼠标位置更新射线
            rayCaster.setFromCamera(pointer, camera)
            // 计算物体和射线的交点
            console.log(this.list, 'this.list');
            const list = rayCaster.intersectObjects(this.list)
            // obj是射线交互收集到的对象，obj.object才是threejs对象
            list.forEach(obj => {
                // 通过物体拿到对应的回调函数
                const fn = this.map.get(obj.object)
                // 执行回调函数，传回threejs三维物体
                fn(obj.object)
            })

        })

    }

    addMesh (mesh, fn) {
        this.list.push(mesh)
        this.map.set(mesh, fn)
    }
}